// pages/join-room/join-room.js
const app = getApp();

Page({
  data: {
    roomCode: '',
    isLoading: false,
    errorMessage: ''
  },

  onLoad: function(options) {
    // 如果有房间码参数，则自动填充
    if (options.roomCode) {
      this.setData({
        roomCode: options.roomCode
      });
      this.joinRoom();
    }
  },

  // 输入房间号
  inputRoomCode: function(e) {
    // 只允许输入数字
    const value = e.detail.value.replace(/[^0-9]/g, '');
    this.setData({
      roomCode: value,
      errorMessage: ''
    });
  },

  // 清除输入
  clearInput: function() {
    this.setData({
      roomCode: '',
      errorMessage: ''
    });
  },

  // 加入房间
  joinRoom: function() {
    const { roomCode } = this.data;
    
    // 验证房间号
    if (!roomCode || roomCode.length !== 6) {
      this.setData({
        errorMessage: '请输入6位数字房间号'
      });
      return;
    }
    
    // 防止重复提交
    if (this.data.isLoading) return;
    
    this.setData({
      isLoading: true,
      errorMessage: ''
    });
    
    // 调用接口加入房间
    wx.request({
      url: app.globalData.apiBaseUrl + '/room/join',
      method: 'POST',
      header: {
        'Authorization': 'Bearer ' + app.globalData.token
      },
      data: {
        room_code: roomCode
      },
      success: (res) => {
        if (res.data.code === 200) {
          // 加入成功，跳转到房间详情页
          wx.navigateTo({
            url: '/pages/room-detail/room-detail?room_id=' + res.data.data.room_id
          });
        } else {
          this.setData({
            errorMessage: res.data.message || '加入房间失败',
            isLoading: false
          });
        }
      },
      fail: (err) => {
        console.error('加入房间失败:', err);
        this.setData({
          errorMessage: '网络错误，请检查网络连接',
          isLoading: false
        });
      },
      complete: () => {
        this.setData({
          isLoading: false
        });
      }
    });
  },

  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  },

  // 扫码加入
  scanQRCode: function() {
    const that = this;
    
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        // 解析二维码内容
        const result = res.result;
        
        try {
          // 尝试解析JSON格式的二维码内容
          const qrData = JSON.parse(result);
          if (qrData.type === 'room' && qrData.room_code) {
            that.setData({
              roomCode: qrData.room_code
            });
            that.joinRoom();
          } else {
            wx.showToast({
              title: '无效的房间二维码',
              icon: 'none'
            });
          }
        } catch (e) {
          // 如果不是JSON格式，尝试直接作为房间码处理
          if (/^\d{6}$/.test(result)) {
            that.setData({
              roomCode: result
            });
            that.joinRoom();
          } else {
            wx.showToast({
              title: '无效的房间二维码',
              icon: 'none'
            });
          }
        }
      },
      fail: (err) => {
        if (err.errMsg !== 'scanCode:fail cancel') {
          wx.showToast({
            title: '扫码失败，请重试',
            icon: 'none'
          });
        }
      }
    });
  }
});